package com.gagakuai.executor;

import com.gagakuai.base.BaseRequest;
import com.gagakuai.base.vo.Result;
import com.gagakuai.exception.BizException;
import com.gagakuai.template.CallBackTemplate;
import com.gagakuai.template.ExecutorTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/*
 * service执行模板
 * @author JianBai
 * @date 2022/10/22 22:44
 */
@Component
public class ServiceExecutorImpl implements ExecutorTemplate {


    private static final Logger LOGGER = LoggerFactory.getLogger("SERVICE_LOG");

    @Override
    public Result<?> execute(BaseRequest req, CallBackTemplate<?> callBack) {

        Result<Object> result = new Result<>();

        try {
            callBack.checkParam();
            Object resultData = callBack.execute();
            result.setResult(resultData);
        }catch (BizException ex){
            LOGGER.warn("{}请求业务异常, req:{}, ex:{}",req.getReqType(), req, ex);
            result.setCode(ex.getStatus());
            result.setMessage(ex.getMessage());
            result.setSuccess(false);
            return result;
        }catch (Exception ex){
            LOGGER.warn("{}请求系统异常, req:{}, ex:{}",req.getReqType(), req, ex);
            result.setCode(500);
            result.setMessage("系统繁忙, 请稍后再试");
            result.setSuccess(false);
            return result;
        }catch (Throwable e){
            LOGGER.error("{}请求服务器异常, req:{}, ex:{}",req.getReqType(), req, e);
            result.setCode(500);
            result.setMessage("服务器繁忙, 请稍后再试");
            result.setSuccess(false);
            return result;
        }
        result.setCode(200);
        result.setSuccess(true);
        // ---流白
        LOGGER.info("{}调用完成, 耗时:{}",req.getReqType(), System.currentTimeMillis() - req.getTimestamp());

        return result;
    }
}
